﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls.Charting;
using Telerik.Windows.Data;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Controls;
using FarmacieDAL;
using Microsoft.Win32;

namespace Farmacie.Controls
{
    /// <summary>
    /// Interaction logic for ArhivaGraphic.xaml
    /// </summary>
    public partial class ArhivaGraphic : UserControl
    {
        SolidColorBrush foreground = new SolidColorBrush(Color.FromArgb(255, 204, 204, 204));

        public ArhivaGraphic()
        {
            InitializeComponent();

            RadChart1.BorderBrush = new SolidColorBrush(Colors.Transparent);
            RadChart1.DefaultView.ChartArea.NoDataString = "Grupati dupa o coloana.";
            RadChart1.DefaultView.ChartLegendPosition = Dock.Bottom;
            RadChart1.DefaultView.ChartLegend.BorderThickness = new Thickness(0); 
            RadChart1.DefaultView.ChartLegend.Header = ""; 

            RadGridView1.Grouped += this.RadGridView1_Grouped;

            RadGridView1.CanUserSortColumns = false;
            RadGridView1.CanUserFreezeColumns = false;
            RadGridView1.IsFilteringAllowed = false;
            RadGridView1.CanUserResizeColumns = false;
            
            RadGridView1.IsReadOnly = true;
            RadGridView1.BorderThickness = new Thickness(0);

            this.Loaded += this.ArhivaGraphic_Loaded;
            this.cmbAggregation.SelectionChanged += cmbAggregation_SelectionChanged;
            RadGridView1.AutoGeneratingColumn += this.RadGridView1_AutoGeneratingColumn;
            comboExport.ItemsSource = exportTypes;
            buttonExport.Click += buttonExport_Click;
        }

        private void ArhivaGraphic_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshControl();
        }

        public void RefreshControl()
        {
            ArhivaManager.Refresh();
            RadChart1.ItemsSource = null;
            RadGridView1.ItemsSource = ArhivaGraphic.GenerateData();
        }

        private void RadGridView1_AutoGeneratingColumn(object sender, Telerik.Windows.Controls.GridViewAutoGeneratingColumnEventArgs e)
        {
            if (e.Column.UniqueName == "Cantitate")
                e.Column.IsGroupable = false;
        }

        private void RadGridView1_Grouped(object sender, Telerik.Windows.Controls.GridViewGroupedEventArgs e)
        {
            this.BindChart();
        }

        private void BindChart()
        {
            RadChart1.ItemsSource = null;
            RadChart1.SeriesMappings.Clear();

            SeriesMapping mapping1 = new SeriesMapping();

            ChartAggregateFunction aggFunct = (ChartAggregateFunction)Enum.Parse(typeof(ChartAggregateFunction), (this.cmbAggregation.SelectedItem as RadComboBoxItem).Content as string, true);

            mapping1.ItemMappings.Add(new ItemMapping("Cantitate", DataPointMember.YValue, aggFunct));
            mapping1.SeriesDefinition = new BarSeriesDefinition();

            foreach (IGroupDescriptor descriptor in RadGridView1.GroupDescriptors)
            {
                mapping1.GroupingSettings.GroupDescriptors.Add(new ChartGroupDescriptor(this.GetDataMemberName(descriptor)));
            }

            if (RadGridView1.GroupDescriptors.Count > 1 && (cmbAggregation.SelectedItem as RadComboBoxItem).Content.ToString().ToLower() != "none")
            {
                IGroupDescriptor lastGroupDescriptor = RadGridView1.GroupDescriptors[RadGridView1.GroupDescriptors.Count - 1];
                mapping1.ItemMappings.Add(new ItemMapping(this.GetDataMemberName(lastGroupDescriptor), DataPointMember.XCategory));
            }

            RadChart1.SeriesMappings.Add(mapping1);
            RadChart1.ItemsSource = RadGridView1.Items;
        }

        private string GetDataMemberName(IGroupDescriptor descriptor)
        {
            if (descriptor is GroupDescriptor)
            {
                return (descriptor as GroupDescriptor).Member;
            }
            
            if (descriptor is ColumnGroupDescriptor)
            {
                GridViewDataColumn column = ((ColumnGroupDescriptor)descriptor).Column as GridViewDataColumn;
                return column.GetDataMemberName();
            }

            return null;
        }

        private static List<Arhiva> GenerateData()
        {
            return ArhivaManager.ToateArhivele;
        }

        private void cmbAggregation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.BindChart();
        }

        private void SetDefaultGroupDescriptors()
        {
            RadGridView1.GroupDescriptors.Clear();

            GroupDescriptor groupDesc = new GroupDescriptor();
            groupDesc.Member = "Year";
            RadGridView1.GroupDescriptors.Add(groupDesc);
        }

        private void SetYearGroupDescriptors()
        {
            RadGridView1.GroupDescriptors.Clear();

            GroupDescriptor groupDesc = new GroupDescriptor();
            groupDesc = new GroupDescriptor();
            groupDesc.Member = "Year";
            RadGridView1.GroupDescriptors.Add(groupDesc);
        }

        #region Export

        string[] exportTypes = new string[] { "PNG", "BMP", "XLSX", "XPS" };

        void buttonExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dialog = PrepareSaveDialog();

            if (!(bool)dialog.ShowDialog())
                return;

            string fileName = dialog.FileName;
            this.ExportTheFile(fileName);
        }

        private void ExportTheFile(string fileName)
        {
            switch (comboExport.SelectedItem.ToString())
            {
                case "PNG":
                    RadChart1.Save(fileName, 96d, 96d, new PngBitmapEncoder());
                    break;

                case "BMP":
                    RadChart1.Save(fileName, 96d, 96d, new BmpBitmapEncoder());
                    break;

                case "XLSX":
                    RadChart1.ExportToExcelML(fileName);
                    break;

                case "XPS":
                    RadChart1.ExportToXps(fileName);
                    break;
                default:
                    RadChart1.Save(fileName, 96d, 96d, new PngBitmapEncoder());
                    break;
            }
        }

        private SaveFileDialog PrepareSaveDialog()
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = comboExport.SelectedValue.ToString().ToLower();
            dialog.Filter = this.GetDefaulExt();
            return dialog;
        }

        private string GetDefaulExt()
        {
            return string.Format("*.{0} | {1} File", comboExport.SelectedValue.ToString().ToLower(), comboExport.SelectedValue.ToString());
        }

        #endregion
    }
}
